<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>跨域资源共享CORS</title>
</head>
<body>
<h1>跨域资源共享CORS</h1>
<p>npx http-server --port=9000</p>
<script>
  // fetch('http://localhost:8080/getUserInfo', {
  //   credentials: 'include', // 前端跨域携带cookie
  // })
  // .then(response => response.json())
  // .then(res => {
  //   console.log(res);
  // })

  var xhr = new XMLHttpRequest(); // IE8/9需用window.XDomainRequest兼容

  // 前端设置是否带cookie
  xhr.withCredentials = true;

  xhr.open('post', 'http://localhost:8080/getUserInfo', true);
  xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  xhr.send('user=admin');

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      console.log('xhr', JSON.parse(xhr.responseText));
    }
  };

  const getData = () => {
    fetch('http://localhost:8080/getUserInfo', {
      credentials: 'include', // 前端跨域携带cookie
    })
    .then(response => response.json())
    .then(res => {
      console.log('fetch', res);
    })
  }
  getData()
</script>
</body>
</html>
